// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
const _ = db.command
const $ = db.command.aggregate

// 云函数入口函数
const appealDetail = async function (params) {
  const wxContext = cloud.getWXContext()

  let appealId = params.appealId

  let appealList = await db.collection('appeal')
    .aggregate()
    // 匹配项
    .match({
      _id: appealId
    })
    // 连表查询 用户信息
    .lookup({
      from: 'user',
      localField: '_openid',
      foreignField: '_openid',
      as: 'userInfo'
    })
    .addFields({
      userInfo: $.arrayElemAt(['$userInfo', 0])
    })

    // 列表查询点赞信息
    .lookup({
      from: 'appealEndorse',
      localField: '_id',
      foreignField: 'appealId',
      as: 'endorses'
    })
    .addFields({
      endorseCount: $.size('$endorses')
    })

    // 列表查询评论信息
    .lookup({
      from: 'appealComment',
      localField: '_id',
      foreignField: 'appealId',
      as: 'comments'
    })
    .addFields({
      commentCount: $.size('$comments')
    })

    // 判断次诉求用户是否点赞
    .addFields({
      isEndorse: $.gt([$.size($.filter({
        input: '$endorses',
        as: 'item',
        cond: $.eq(['$$item._openid', wxContext.OPENID])
      })), 0])
    })

    // 去掉或者重置 一些值
    .project({
      endorses: false,
      comments: false
    })
    .end()

    return appealList.list[0]


}

module.exports = appealDetail